package com.lujieni.async.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import java.util.concurrent.Future;

/**
 * @Auther lujieni
 * @Date 2020/5/20
 */
@Service
public class AsyncTask {

    @Async
    public Future<Boolean> task1() throws InterruptedException{
        System.out.println("task1开始");
        System.out.println(Thread.currentThread().getName()); //另一个线程 task-1
        long start = System.currentTimeMillis();
        Thread.sleep(1000);
        long end = System.currentTimeMillis();
        System.out.println("task1任务耗时"+ (end-start) + "ms");
        return new AsyncResult<>(true);
    }

    @Async
    public Future<Boolean> task2() throws InterruptedException{
        System.out.println("task2开始");
        System.out.println("task2:"+Thread.currentThread().getName()); //另一个线程 task-2
        long start = System.currentTimeMillis();
        Thread.sleep(2000);
        long end = System.currentTimeMillis();
        System.out.println("task2任务耗时"+ (end-start) +"ms");
        return new AsyncResult<>(false);

    }

    /**
     * @Description:
     * 加了@Async的签的话 外部调用work就是异步的,但即使
     * task2方法也有@Async标签,但本类方法的互相调用会导致@Async失效
     * 因此在work方法中是串行的
     * @param
     * @return:
     * @Author: lujieni
     * @Date: 2021/3/30
     */
    @Async
    public void work() throws InterruptedException{
        System.out.println("work:"+Thread.currentThread().getName()); //另一个线程
        long start = System.currentTimeMillis();
        Thread.sleep(3000);
        long end = System.currentTimeMillis();
        System.out.println("work任务耗时"+(end-start)+"ms");

        task2(); //本类中互相调用即使带有@Async标签也是同步的

    }
}
